import { Input } from '@/components/ui/input';
import MenuToggle from '../components/MenuToggle';
import { CardContent, CardHeader, Card, CardTitle } from '@/components/ui/card';
import { Textarea } from '@/components/ui/textarea';
import { SelectItem, Select, SelectContent, SelectValue, SelectTrigger } from '@/components/ui/select';
import { User, Shield, Calendar, MapPin, Edit, Mail, Phone, X, Save, Camera, Key, LogOut } from 'lucide-react';
import React, { useState, useEffect, useCallback } from 'react';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { useNavigate } from 'react-router-dom';
import { userApi } from '@/services/api';
import ChangePasswordDialog from '@/components/ChangePasswordDialog';

const Profile = ({ toggleSidebar }) => {
  const navigate = useNavigate();
  const [isEditing, setIsEditing] = useState(false);
  const [showPasswordDialog, setShowPasswordDialog] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);

  // 用户信息状态
  const [userInfo, setUserInfo] = useState({
    nickName: '',
    realName: '',
    email: '',
    phone: '',
    sex: 'N',
    avatar: '',
    userId: null,
    enabled: true,
    currentRoleName: '',
    currentRoleId: null,
    lastLoginAt: '',
    defaultRoleId: null,
    username: '',
    bio: '',
    joinDate: ''
  });

  // 获取用户信息
  const fetchUserInfo = useCallback(async () => {
    setIsLoading(true);
    try {
      const response = await userApi.getSelfInfo();
      if (response.code === "200" && response.msg === "success" && response.data) {
        const userData = response.data;
        setUserInfo(prev => ({
          ...prev,
          ...userData,
          sex: userData.sex || 'N',
          bio: userData.bio || '',
          joinDate: userData.joinDate || new Date().toISOString().split('T')[0]
        }));
        
        const storage = localStorage.getItem('authToken') ? localStorage : sessionStorage;
        storage.setItem('userInfo', JSON.stringify(userData));
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      const storage = localStorage.getItem('authToken') ? localStorage : sessionStorage;
      const cachedUserInfo = storage.getItem('userInfo');
      if (cachedUserInfo) {
        try {
          const userData = JSON.parse(cachedUserInfo);
          setUserInfo(prev => ({ ...prev, ...userData }));
        } catch (parseError) {
          console.error('解析缓存用户信息失败:', parseError);
        }
      }
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchUserInfo();
  }, [fetchUserInfo]);

  const handleSaveProfile = async () => {
    setIsSaving(true);
    try {
      console.log('保存用户信息:', userInfo);
      
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const storage = localStorage.getItem('authToken') ? localStorage : sessionStorage;
      storage.setItem('userInfo', JSON.stringify(userInfo));
      
      setIsEditing(false);
      alert('个人信息保存成功');
    } catch (error) {
      console.error('保存用户信息失败:', error);
      alert('保存失败，请稍后重试');
    } finally {
      setIsSaving(false);
    }
  };

  const handleAvatarChange = (event) => {
    const file = event.target.files[0];
    if (file) {
      if (file.size > 2 * 1024 * 1024) {
        alert('头像文件大小不能超过2MB');
        return;
      }
      
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件');
        return;
      }
      
      const reader = new FileReader();
      reader.onload = (e) => {
        setUserInfo(prev => ({ ...prev, avatar: e.target.result }));
      };
      reader.readAsDataURL(file);
    }
  };

  const handleLogout = () => {
    console.log('用户注销登录');
    localStorage.removeItem('authToken');
    localStorage.removeItem('refreshToken');
    localStorage.removeItem('tokenExpires');
    localStorage.removeItem('userInfo');
    sessionStorage.removeItem('authToken');
    sessionStorage.removeItem('refreshToken');
    sessionStorage.removeItem('tokenExpires');
    sessionStorage.removeItem('userInfo');
    navigate('/authority/login');
  };

  const getSexLabel = (sex) => {
    switch (sex) {
      case 'M': return '男';
      case 'F': return '女';
      default: return '未设置';
    }
  };

  const formatLastLoginTime = (lastLoginAt) => {
    if (!lastLoginAt) return '从未登录';
    try {
      const date = new Date(lastLoginAt);
      return date.toLocaleString('zh-CN');
    } catch (error) {
      return lastLoginAt;
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="w-8 h-8 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-material-grey-600">加载用户信息中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-screen overflow-x-hidden">
      {/* 头部工具栏 - 固定 */}
      <div className="flex-shrink-0 mt-3">
        <div className="px-4 py-4">
          <div className="flex items-center space-x-4">
            <MenuToggle onClick={toggleSidebar} />
            
            <div className="flex items-center space-x-3">
              <div className="w-10 h-10 bg-gradient-to-br from-primary to-primary-600 rounded-xl flex items-center justify-center">
                <User className="w-6 h-6 text-white" />
              </div>
              <div>
                <h1 className="text-2xl font-bold text-material-grey-800">
                  个人资料
                </h1>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 操作按钮栏 - 固定 */}
      <div className="flex-shrink-0">
        <div className="px-4 py-3 mx-[1%]">
          <div className="flex items-center justify-end space-x-3">
            {isEditing ? (
              <>
                <Button variant="outline" onClick={() => setIsEditing(false)} disabled={isSaving}>
                  <X className="w-4 h-4 mr-2" />
                  取消
                </Button>
                <Button onClick={handleSaveProfile} disabled={isSaving} className="bg-gradient-to-r from-primary to-primary-600 hover:from-primary-600 hover:to-primary-700">
                  {isSaving ? (
                    <>
                      <div className="w-4 h-4 mr-2 border-2 border-white border-t-transparent rounded-full animate-spin" />
                      保存中...
                    </>
                  ) : (
                    <>
                      <Save className="w-4 h-4 mr-2" />
                      保存
                    </>
                  )}
                </Button>
              </>
            ) : (
              <>
                <Button onClick={() => setIsEditing(true)} className="bg-gradient-to-r from-primary to-primary-600 hover:from-primary-600 hover:to-primary-700">
                  <Edit className="w-4 h-4 mr-2" />
                  编辑资料
                </Button>
                <Button 
                  variant="destructive" 
                  onClick={handleLogout}
                  className="bg-red-600 hover:bg-red-700"
                >
                  <LogOut className="w-4 h-4 mr-2" />
                  注销登录
                </Button>
              </>
            )}
          </div>
        </div>
      </div>

      {/* 主内容区域 - 可滚动 */}
      <div className="flex-1 overflow-y-auto overflow-x-hidden px-4 pb-6 mx-[1%]">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* 左侧：基本信息 */}
          <div className="lg:col-span-2 space-y-6">
            {/* 个人信息卡片 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <User className="w-5 h-5" />
                  <span>基本信息</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* 头像部分 */}
                <div className="flex items-center space-x-6">
                  <div className="relative">
                    <div className="w-24 h-24 bg-gradient-to-br from-primary to-primary-600 rounded-full flex items-center justify-center overflow-hidden">
                      {userInfo.avatar ? (
                        <img 
                          src={userInfo.avatar} 
                          alt="头像" 
                          className="w-full h-full object-cover"
                        />
                      ) : (
                        <span className="text-2xl font-bold text-white">
                          {userInfo.nickName?.charAt(0) || userInfo.realName?.charAt(0) || userInfo.username?.charAt(0) || '用'}
                        </span>
                      )}
                    </div>
                    {isEditing && (
                      <label className="absolute bottom-0 right-0 w-8 h-8 bg-white rounded-full shadow-material-2 flex items-center justify-center cursor-pointer hover:bg-material-grey-50 transition-colors">
                        <Camera className="w-4 h-4 text-material-grey-600" />
                        <input
                          type="file"
                          accept="image/*"
                          onChange={handleAvatarChange}
                          className="hidden"
                        />
                      </label>
                    )}
                  </div>
                  <div>
                    <h3 className="text-xl font-semibold text-material-grey-900">
                      {userInfo.nickName || userInfo.realName || userInfo.username}
                    </h3>
                    <div className="flex items-center space-x-2 mt-2">
                      <div className={`w-2 h-2 rounded-full ${userInfo.enabled ? 'bg-green-500' : 'bg-red-500'}`}></div>
                      <span className={`text-xs ${userInfo.enabled ? 'text-green-600' : 'text-red-600'}`}>
                        {userInfo.enabled ? '账户正常' : '账户禁用'}
                      </span>
                      {userInfo.currentRoleName && (
                        <>
                          <span className="text-xs text-material-grey-400">·</span>
                          <span className="text-xs text-material-grey-600">{userInfo.currentRoleName}</span>
                        </>
                      )}
                    </div>
                  </div>
                </div>

                {/* 基本信息表单 */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="nickName">昵称</Label>
                    <Input
                      id="nickName"
                      value={userInfo.nickName}
                      onChange={(e) => setUserInfo(prev => ({ ...prev, nickName: e.target.value }))}
                      disabled={!isEditing}
                    />
                  </div>
                  <div>
                    <Label htmlFor="realName">真实姓名</Label>
                    <Input
                      id="realName"
                      value={userInfo.realName}
                      onChange={(e) => setUserInfo(prev => ({ ...prev, realName: e.target.value }))}
                      disabled={!isEditing}
                    />
                  </div>
                  <div>
                    <Label htmlFor="email">邮箱</Label>
                    <Input
                      id="email"
                      type="email"
                      value={userInfo.email}
                      onChange={(e) => setUserInfo(prev => ({ ...prev, email: e.target.value }))}
                      disabled={!isEditing}
                    />
                  </div>
                  <div>
                    <Label htmlFor="phone">手机号</Label>
                    <Input
                      id="phone"
                      value={userInfo.phone}
                      onChange={(e) => setUserInfo(prev => ({ ...prev, phone: e.target.value }))}
                      disabled={!isEditing}
                    />
                  </div>
                  <div>
                    <Label htmlFor="sex">性别</Label>
                    <Select 
                      value={userInfo.sex} 
                      onValueChange={(value) => setUserInfo(prev => ({ ...prev, sex: value }))}
                      disabled={!isEditing}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="请选择性别" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="M">男</SelectItem>
                        <SelectItem value="F">女</SelectItem>
                        <SelectItem value="N">未设置</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label htmlFor="username">用户名</Label>
                    <Input
                      id="username"
                      value={userInfo.username}
                      disabled={true}
                      className="bg-material-grey-50"
                    />
                    <p className="text-xs text-material-grey-500 mt-1">用户名不可修改</p>
                  </div>
                </div>

                <div>
                  <Label htmlFor="bio">个人简介</Label>
                  <Textarea
                    id="bio"
                    value={userInfo.bio}
                    onChange={(e) => setUserInfo(prev => ({ ...prev, bio: e.target.value }))}
                    disabled={!isEditing}
                    rows={3}
                    placeholder="介绍一下自己..."
                  />
                </div>
              </CardContent>
            </Card>

            {/* 安全设置卡片 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Shield className="w-5 h-5" />
                  <span>安全设置</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between">
                  <div>
                    <h4 className="font-medium text-material-grey-900">密码</h4>
                    <p className="text-sm text-material-grey-600">
                      {userInfo.lastLoginAt ? `上次登录：${formatLastLoginTime(userInfo.lastLoginAt)}` : '从未登录'}
                    </p>
                  </div>
                  <Button 
                    variant="outline" 
                    onClick={() => setShowPasswordDialog(true)}
                  >
                    <Key className="w-4 h-4 mr-2" />
                    修改密码
                  </Button>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 右侧：账户统计 */}
          <div className="space-y-6">
            {/* 账户统计 */}
            <Card>
              <CardHeader>
                <CardTitle>账户统计</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-material-grey-600">用户ID</span>
                  <span className="text-sm font-medium">{userInfo.userId || '-'}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-material-grey-600">当前角色</span>
                  <span className="text-sm font-medium">{userInfo.currentRoleName || '未分配'}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-material-grey-600">性别</span>
                  <span className="text-sm font-medium">{getSexLabel(userInfo.sex)}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-material-grey-600">账户状态</span>
                  <span className={`text-sm font-medium ${userInfo.enabled ? 'text-green-600' : 'text-red-600'}`}>
                    {userInfo.enabled ? '正常' : '禁用'}
                  </span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-material-grey-600">最后登录</span>
                  <span className="text-sm font-medium">
                    {userInfo.lastLoginAt ? formatLastLoginTime(userInfo.lastLoginAt) : '从未登录'}
                  </span>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>

      {/* 修改密码对话框 */}
      <ChangePasswordDialog 
        open={showPasswordDialog}
        onOpenChange={setShowPasswordDialog}
      />
    </div>
  );
};

export default Profile;
